<template>
  <el-radio-group v-model="model" size="mini" :disabled="disabled" @change="onChange">
    <template v-if="radioType === 'radio'">
      <el-radio v-for="(item,index) in datas" :key="index" :label="item.value">{{item.label}}</el-radio>
    </template>
    <template v-else>
      <el-radio-button v-for="(item,index) in datas" :key="index" :label="item.value">{{item.label}}</el-radio-button>
    </template>
  </el-radio-group>
</template>

<script>
import { mapState, mapActions } from 'vuex'
export default {
  name: 'yc-dict-radio',
  props: {
    value: {
      type: [Number, String, Array],
      default: null
    },
    dictName: {
      type: String,
      default: '',
      required: false
    },
    radioType: {
      type: String,
      default: 'radio'
    },
    // [自动加载字典] 自定义字典数据 设置为 false 时会自动加载对应名称的字典
    customDict: {
      type: Boolean,
      default: false,
      required: false
    },
    options: {
      type: Array,
      default: function () {
        return []
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    onChange: {
      type: Function,
      default: function () {

      }
    }
  },
  data () {
    return {
      datas: []
    }
  },
  computed: {
    ...mapState('ycAdmin/dict', [
      'dicts'
    ]),
    model: {
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
        this.$emit('change', val)
      }
    },
    listeners () {
      return {
        ...this.$listeners
      }
    }
  },
  watch: {
    dicts () {
      this.reload()
    },
    dictName: {
      handler () {
        if (!this.customDict) this.fetch()
        this.reload()
      },
      immediate: true
    },
    options: {
      handler () {
        if (this.customDict) {
          this.reload()
        }
      },
      immediate: true
    }
  },
  methods: {
    ...mapActions('ycAdmin/dict', {
      dictGet: 'get',
      dictFetch: 'fetch'
    }),
    fetch () {
      this.dictFetch(this.dictName)
    },
    async reload () {
      // 从全局状态管理中获取字典值的列表
      if (this.customDict) {
        this.datas = this.$_.cloneDeep(this.options)
      } else {
        const options = this.$_.cloneDeep(await this.dictGet(this.dictName))
        this.datas = options.map(e => {
          var value = e.value
          if (e.dictType === 1) {
            value = parseInt(e.value)
          } else if (e.dictType === 3) {
            value = e.value === 'true'
          }
          return {
            label: e.label,
            value: value
          }
        })
      }
    }
  }
}
</script>
